import math
import pygame,sys

import pygame

def calculate_new_coordinates(old_x, old_y, old_screen_width, old_screen_height, new_screen_width, new_screen_height):
    new_x = int((old_x / old_screen_width) * new_screen_width)
    new_y = int((old_y / old_screen_height) * new_screen_height)
    return new_x, new_y

# 原始屏幕的尺寸
old_screen_width = 1680
old_screen_height = 1050

# 原始点坐标
old_coordinates = [
    (840, 126),
    (1390, 384),
    (1294, 924),
    (374, 924),
    (284, 384),
    (1080, 548),
    (835, 678),
    (593, 549),
    (689, 384),
    (986, 384)
]

def retnewsizewindowcoord( new_screen_width, new_screen_height ):
    # 计算新的点坐标
    new_coordinates = []
    for old_x, old_y in old_coordinates:
        new_x, new_y = calculate_new_coordinates(old_x, old_y, old_screen_width, old_screen_height, new_screen_width, new_screen_height)
        new_coordinates.append((new_x, new_y))
    return new_coordinates


# 打印字体名称
defkaiti = 'kaiti'
kaitifound = 0
gb2312 = 'gb2312'
for font in pygame.font.get_fonts():
    print(font)
    if font.find(defkaiti) != -1:
        print('<------')
        kaitifound = 1
        defkaiti = font        
    if font.find(gb2312) != -1:
        print('<------')
        gb2312 = font

if kaitifound == 0:
    defkaiti = gb2312

pygame.init()    
pygame.font.init()
screen_info = pygame.display.Info()
font  =  pygame.font.SysFont(defkaiti,int(screen_info.current_h*0.19*2.5))
font2  =  pygame.font.SysFont(defkaiti,int(screen_info.current_h*0.05*2.5))

def textcenter(screen,  text, top=-1 ):
    if check_first(): return
    if top == -1:
        text_sf  =  font.render(text,True,pygame.Color(255,0,0),None)
    elif top > 0:
        text_sf  =  font2.render(text,True,pygame.Color(255,0,0),None)
    # 获取文本的矩形区域
    text_rect = text_sf.get_rect()

    # 获取屏幕分辨率
    screen_info = pygame.display.Info()
    screen_width, screen_height = screen_info.current_w, screen_info.current_h

    if top == -1:
        # 将文本矩形区域居中
        text_rect.center = ((int)(screen_width // 2), screen_height // 2)
    elif top > 0:
        # 将文本矩形区域居中
        text_rect.center = ((int)(screen_width // 2), top)

    screen.blit(text_sf,text_rect)


# 棋盘的位置数据
POSITION = { 0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9 }
ADJACENT = {
        0: [9, 5],
        1: [5, 6],
        2: [6, 7],
        3: [7, 8],
        4: [8, 9],
        5: [6, 3],
        6: [7, 4],
        7: [8, 0],
        8: [9, 1],
        9: [5, 2],
    }

current_piece = -1

def checkfinish():
    for i in range(10):
        if POSITION[ADJACENT[i][0]] != -1:
            if POSITION[i] == -1 and POSITION[ADJACENT[i][1]] != -1:
                return None
            if POSITION[i] != -1 and POSITION[ADJACENT[i][1]] == -1:
                return None
    if checksuccess():
        print( "count = 1!" )
        if POSITION[0] != -1:
            print( "吉星高照！" )
            return '吉星高照'
        if POSITION[6] != -1:
            print( "心想事成！" )
            return '心想事成'
    else:
        print( "count > 1!" )
        return '失败'
    return '成功'

def checksuccess():
    count = 0
    for i in range(10):
        if POSITION[i] != -1:
            count += 1
    return count == 1

def check_first():
    for i in range(10):
        if POSITION[i] == -1:
            return False
    return True

def canjump( cur, empty ):
    for i in range(10):
        if i == cur and ADJACENT[i][1] == empty or i == empty and ADJACENT[i][1] == cur:
            if POSITION[ADJACENT[i][0]] != -1: # 中间有棋子
                POSITION[empty] = POSITION[cur]
                POSITION[cur] = -1
                current_piece = empty
                POSITION[ADJACENT[i][0]] = -1 # 删除中间的棋子

def modify_piecesstatus( pos, screen ):
    global current_piece
    if check_first():
        POSITION[pos] = -1
    else:
        if POSITION[pos] != -1: # 选的不是空位，修改当前棋子
            current_piece = pos
        else: # 选的是空位
            if current_piece != -1:  # 检查当前选择棋子选了没
                canjump( current_piece, pos )
    print( "current_piece:", current_piece )
    str = checkfinish()
    if str != None:
        print( "is finished!", str )

def getposiempty( pos ):
    return POSITION[pos] != -1

def getposselected( pos ):
    return current_piece == pos

def calculate_intersection(segment1, segment2):
    # 线段1的起点和终点
    P1, P2 = segment1[0], segment1[1]
    # 线段2的起点和终点
    P3, P4 = segment2[0], segment2[1]

    # 计算斜率
    m1 = (P2[1] - P1[1]) / (P2[0] - P1[0]) if (P2[0] - P1[0]) != 0 else None
    m2 = (P4[1] - P3[1]) / (P4[0] - P3[0]) if (P4[0] - P3[0]) != 0 else None

    # 判断线段关系
    if m1 is None and m2 is None:
        # 两条线段都是垂直线段且平行，无交点
        return None
    elif m1 is None:
        # 线段1是垂直线段，线段2不是
        intersection_x = P1[0]
        intersection_y = m2 * (intersection_x - P3[0]) + P3[1]
        return (intersection_x, intersection_y)
    elif m2 is None:
        # 线段2是垂直线段，线段1不是
        intersection_x = P3[0]
        intersection_y = m1 * (intersection_x - P1[0]) + P1[1]
        return (intersection_x, intersection_y)
    elif m1 == m2:
        # 两条线段平行，无交点
        return None
    else:
        # 计算交点的 x 坐标
        intersection_x = (m1 * P1[0] - m2 * P3[0] - P1[1] + P3[1]) / (m1 - m2)
        # 计算交点的 y 坐标
        intersection_y = m1 * (intersection_x - P1[0]) + P1[1]
        return (intersection_x, intersection_y)



pygame.display.set_caption("九子贤棋")

class Button:
    def __init__(self, text, position):
        self.text = text
        self.position = position
        self.font = pygame.font.Font(None, 36)
        self.rect = pygame.Rect(position[0], position[1], 36, 39)

    def draw(self, surface):
        pygame.draw.rect(surface, (199, 199, 199), self.rect)
        text_surface = self.font.render(self.text, True, (0, 0, 0))
        surface.blit(text_surface, (self.position[0] + 10, self.position[1] + 9))

    def is_clicked(self, pos):
        if self.rect.collidepoint(pos):
            return True
        return False

class Game:
    def __init__(self):
        self.done = False
        self.won = False
        self.piecespos = []
        
        pygame.init()

        screen_info = pygame.display.Info()
        self.size = (screen_info.current_w, screen_info.current_h)
        width, height = self.size
        self.piecesize = min(width, height) / 10

        self.green = (0, 155, 0)
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

        # 创建按钮实例
        self.close_button = Button("X", (10, 10))

        # adding mouse focus
        self.focus = -1

    def getXbtnpressed(self):
        mouse_pos = pygame.mouse.get_pos()
        # 检查按钮是否被点击
        if self.close_button.is_clicked(mouse_pos):
            print( "close X" )
            pygame.quit()
            sys.exit()

    def run_game(self):
        pygame.init()

        width, height = self.size
        radius = min(width, height) * 0.9 / 2
        self.piecesize = radius / 8

        self.piecespos = self.draw_board(radius)

        pygame.display.flip()

        while not self.done:
            repaint = False
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        self.getXbtnpressed()
                        pos = self.get_clicked_position()
                        print(pos)
                        if pos != -1:
                            modify_piecesstatus( pos, self.screen )
#                            if checkfinish(): return
                        repaint = True
                elif event.type == pygame.MOUSEMOTION:
                    pos = self.get_clicked_position()
                    print("move = ",pos)
                    # 进行鼠标移动的处理逻辑
                    if pos != self.focus:
                        repaint = True
                        self.focus = pos
                       
            if repaint:
                self.draw_board(radius)
            str = checkfinish()
            if str != None:
                if len(str) > 2:
                    top = self.piecespos[0][1]
                    textcenter( self.screen, str, int(top) )
                    textcenter( self.screen, "成功" )
                else:
                    textcenter( self.screen, str )
            pygame.display.flip()

    def get_clicked_position(self):
        mouse_pos = pygame.mouse.get_pos()

#        for i, point in enumerate(self.pieces):
#            print( i, point[0], point[1] )
        for i, point in enumerate(self.piecespos):
            x, y = int(point[0]), int(point[1])
            print( x, y )
            distance = ((mouse_pos[0] - x) ** 2 + (mouse_pos[1] - y) ** 2) ** 0.5
            if distance <= self.piecesize:
                return i
        return -1  # 如果没有点击在任何圆内，则返回-1表示无效点击

    def draw_board(self, radius):
#        self.screen.fill(self.green)
        width, height = self.size

        # 加载背景图像
        background_image = pygame.image.load("xiaoyustar.jpg")
        coin_image = pygame.image.load("coin.png")
        coinup_image = pygame.image.load("coinup.png")

        # 获取图像尺寸
        background_width, background_height = background_image.get_rect().size
        coin_width, coin_height = coin_image.get_rect().size
        ratio = width/background_width

        # 缩放背景图像以适应屏幕大小
        scaled_bg = pygame.transform.scale(background_image, (width, height))
        coin_top = pygame.transform.scale(coin_image, (int(coin_width*ratio), int(coin_height*ratio)))
        coinup_top = pygame.transform.scale(coinup_image, (int(coin_width*ratio), int(coin_height*ratio)))

        # 将背景图像绘制在屏幕上
        self.screen.blit(scaled_bg, (0, 0))  # 贴背景图像

        star_points = []
        intersection_points = []


        absret = retnewsizewindowcoord( width, height )
        print( absret )

        angle = math.radians(360 / 5)

        for i in range(5):
            x = radius * math.cos(i * angle - math.radians(90))
            y = radius * math.sin(i * angle - math.radians(90))
            if i==0: 
                y += height * 0.07
            if i==1 or i==4:
                y += height * 0.005 
                if i==1:
                    x += width * 0.06
                if i==4:
                    x -= width * 0.063
            if i==2 or i==3:
                y += height * 0.016
                if i==2:
                    x += width * 0.105
                if i==3:
                    x -= width * 0.112
#            star_points.append((width/2 + x, height/2 + y, self.white, i))
            star_points.append((absret[i][0], absret[i][1], self.white, i))

#        for i in range(5):
#            pygame.draw.line(self.screen, self.black, star_points[i][:2], star_points[(i + 2) % 5][:2], 3)

        for i in range(5):
            intersection_segment = [star_points[i][:2], star_points[(i + 2) % 5][:2]]
            intersection = calculate_intersection(intersection_segment, [star_points[(i + 1) % 5][:2],
                                                                           star_points[(i + 3) % 5][:2]])
            if intersection is not None:
                intersection_points.append(intersection)

        piecesize = int(self.piecesize)

        tmpidx = 0

        for point in star_points:
            x = int(point[0])
            y = int(point[1])
            if getposiempty( tmpidx ):
                if getposselected(tmpidx) or self.focus == tmpidx:
                    color = self.white
                    coin = coinup_top
                else:
                    color = self.black
                    coin = coin_top
                coin_offsetx = int(coin.get_width()/2)
                coin_offsety = int(coin.get_height()/2)
                self.screen.blit(coin, (x-coin_offsetx,y-coin_offsety))   # 贴硬币图像（x, y为图像在屏幕上的位置）
#                pygame.draw.circle(self.screen, color, (x, y), piecesize, 1)
            tmpidx += 1

        for point in intersection_points:
            x = int(point[0])
            y = int(point[1])
            if tmpidx == 6:
                x += (int)(width * 0.0056)
                y -= (int)(height * 0.005)
            if getposiempty( tmpidx ):
                if getposselected(tmpidx) or self.focus == tmpidx:
                    color = self.white
                    coin = coinup_top
                else:
                    color = self.black
                    coin = coin_top
                coin_offsetx = int(coin.get_width()/2)
                coin_offsety = int(coin.get_height()/2)
                self.screen.blit(coin, (x-coin_offsetx,y-coin_offsety))   # 贴硬币图像（x, y为图像在屏幕上的位置）
#                pygame.draw.circle(self.screen, color, (x,y), piecesize, 1)
            tmpidx += 1

        ret = star_points + intersection_points

#        font = pygame.font.Font(None, 60)
#        for i, point in enumerate(ret):
#            index_text = font.render(str(i), True, pygame.Color("red"))
#            self.screen.blit(index_text, (point[0], point[1]))

        self.close_button.draw(self.screen)

        return ret

    def main(self):
        self.run_game()
        pygame.quit()

if __name__ == "__main__":
    game = Game()
    game.main()
